<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多文件上传 - 文件共享平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a0ca3;
            --light: #f8f9fc;
            --dark: #212529;
            --gray: #6c757d;
            --light-gray: #eaecf4;
            --border: #e3e6f0;
            --text-color-no-dark: #212529; /* 不随深色模式改变的文本颜色 */
        }
        
        [data-theme="dark"] {
            --primary: #5a76ff;
            --primary-dark: #4a5ad4;
            --light: #1a1c23;
            --dark: #f8f9fa;
            --gray: #a0a8b0;
            --light-gray: #252b33;
            --border: #2d333b;
        }
        
        /* 不随深色模式改变颜色的文本 */
        .text-no-dark {
            color: var(--text-color-no-dark);
        }
        
        /* 深色模式下的模态框样式 */
        [data-theme="dark"] .modal-content {
            background-color: var(--light);
            color: var(--dark);
            border-color: var(--border);
        }
        
        [data-theme="dark"] .modal-header {
            border-bottom-color: var(--border);
        }
        
        [data-theme="dark"] .modal-footer {
            border-top-color: var(--border);
        }
        
        [data-theme="dark"] .btn-secondary {
            background-color: var(--light-gray);
            border-color: var(--border);
            color: var(--dark);
        }
        
        /* 深色模式下的消息提示样式 */
        [data-theme="dark"] #message-box .toast {
            background-color: var(--light);
            color: var(--dark);
            border: 1px solid var(--border);
        }
        
        [data-theme="dark"] #message-box .toast-header {
            background-color: var(--light-gray);
            border-bottom-color: var(--border);
        }
        
        .upload-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .upload-card {
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            margin-bottom: 20px;
        }
        
        .upload-header {
            background: linear-gradient(135deg, #4361ee, #3a0ca3);
            color: white;
            padding: 15px 20px;
        }
        
        .upload-body {
            padding: 25px;
            background-color: #f8f9fc;
        }
        
        .drop-zone {
            border: 2px dashed #6c757d;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            background-color: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }
        
        .drop-zone:hover, .drop-zone.drag-over {
            border-color: #4361ee;
            background-color: rgba(67, 97, 238, 0.05);
        }
        
        .file-list {
            max-height: 300px;
            overflow-y: auto;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 10px;
        }
        
        .file-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .file-item:last-child {
            border-bottom: none;
        }
        
        .file-icon {
            width: 40px;
            height: 40px;
            background-color: #e9ecef;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-weight: 500;
            margin-bottom: 3px;
        }
        
        .file-size {
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .progress {
            height: 8px;
            margin-top: 5px;
        }
        
        .file-status {
            font-size: 0.85rem;
            margin-left: 15px;
            min-width: 80px;
            text-align: right;
        }
        
        .status-pending {
            color: #6c757d;
        }
        
        .status-uploading {
            color: #0d6efd;
        }
        
        .status-completed {
            color: #198754;
        }
        
        .status-failed {
            color: #dc3545;
        }
        
        .disk-info {
            background-color: #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .disk-progress {
            height: 10px;
            margin: 10px 0;
        }

        /* 深色模式变量 */
        :root {
          --primary-light: #4361ee;
          --primary-dark: #3a0ca3;
          --light: #f8f9fc;
          --dark: #212529;
          --gray: #6c757d;
          --text-color: #333;
          --bg-color: #f5f7fb;
          --card-bg: #ffffff;
          --header-bg: linear-gradient(135deg, var(--primary-light), var(--primary-dark));
          --border-color: #dee2e6;
          --input-bg: #ffffff;
          --text-muted: #6c757d;
        }
        
        [data-theme="dark"] {
          --primary-light: #5a76ff;
          --primary-dark: #4a5ad4;
          --light: #1a1c23;
          --dark: #f8f9fa;
          --gray: #a0a8b0;
          --text-color: #e0e0e0;
          --bg-color: #121418;
          --card-bg: #1e2229;
          --header-bg: linear-gradient(135deg, #2a3a8d, #1a1a5e);
          --border-color: #2d333b;
          --input-bg: #252b33;
          --text-muted: #a0a8b0;
        }
        
        /* 通用深色模式覆盖 */
        [data-theme="dark"] body {
          background-color: var(--bg-color);
          color: var(--text-color);
        }
        
        [data-theme="dark"] .github-card {
          background-color: var(--card-bg);
          border-color: var(--border-color);
        }
        
        [data-theme="dark"] .github-header {
          background: var(--header-bg);
        }
        
        [data-theme="dark"] .text-muted {
          color: var(--text-muted) !important;
        }
        
        [data-theme="dark"] .form-control {
          background-color: var(--input-bg);
          color: var(--text-color);
          border-color: var(--border-color);
        }
        
        .theme-switch-container {
          position: fixed;
          top: 15px;
          right: 15px;
          z-index: 1000;
        }
        
        #theme-toggle {
          background-color: rgba(255, 255, 255, 0.2);
          color: white;
          border: none;
          box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        
        [data-theme="dark"] #theme-toggle {
          background-color: rgba(0, 0, 0, 0.2);
        }
        
        /* 深色模式下的组件样式 */
        [data-theme="dark"] .upload-card {
          background-color: var(--card-bg);
          border-color: var(--border-color);
        }
        
        [data-theme="dark"] .upload-header {
          background: var(--header-bg);
        }
        
        [data-theme="dark"] .upload-body {
          background-color: var(--card-bg);
        }
        
        [data-theme="dark"] .drop-zone {
          background-color: var(--input-bg);
          border-color: var(--border-color);
        }
        
        [data-theme="dark"] .drop-zone:hover, 
        [data-theme="dark"] .drop-zone.drag-over {
          border-color: var(--primary-light);
          background-color: rgba(90, 118, 255, 0.1);
        }
        
        [data-theme="dark"] .disk-info {
          background-color: var(--input-bg);
        }
        
        [data-theme="dark"] .file-list {
          background-color: var(--input-bg);
          border-color: var(--border-color);
        }
        
        [data-theme="dark"] .file-item {
          border-bottom-color: var(--border-color);
        }
        
        [data-theme="dark"] .file-icon {
          background-color: var(--input-bg);
        }
    </style>
</head>
<body>
    <div class="theme-switch-container">
        <button id="theme-toggle" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-moon"></i> 深色模式
        </button>
    </div>

    <div class="upload-container">
        <div class="upload-card">
            <div class="upload-header">
                <h2><i class="bi bi-cloud-arrow-up"></i> 多文件上传</h2>
                <p class="mb-0">一次上传多个文件到文件共享平台</p>
                    <a href="/index" class="btn btn-light btn-lg">
                        <i class="bi bi-arrow-left me-2 btn-sm "></i> 返回主页
                    </a>
            </div>   

            <div class="upload-body">
                <!-- 磁盘空间信息 -->
                <div class="disk-info">
                    <div class="d-flex justify-content-between">
                        <span>已用空间: <span id="used-space">0B</span></span>
                        <span>可用空间: <span id="free-space">0B</span></span>
                    </div>
                    <div class="disk-progress">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div class="text-center small text-muted">
                        <span id="usage-percent">0%</span> 使用率
                    </div>
                </div>
                
                <!-- 拖放区域 -->
                <div class="drop-zone" id="drop-zone">
                    <i class="bi bi-cloud-arrow-up display-4 text-muted mb-3"></i>
                    <h5>拖放文件到此处</h5>
                    <p class="text-muted">或点击选择文件</p>
                    <input type="file" id="file-input" multiple style="display: none;">
                </div>
                
                <!-- 文件列表 -->
                <div class="file-list" id="file-list">
                    <div class="text-center py-4">
                        <i class="bi bi-folder-plus display-4 text-muted mb-3"></i>
                        <p class="text-muted">暂无文件</p>
                        <p>添加文件开始上传</p>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="d-flex justify-content-between">
                    <button id="clear-btn" class="btn btn-outline-secondary">
                        <i class="bi bi-trash"></i> 清空列表
                    </button>
                    <button id="upload-btn" class="btn btn-primary">
                        <i class="bi bi-cloud-arrow-up"></i> 开始上传
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const dropZone = document.getElementById('drop-zone');
            const fileInput = document.getElementById('file-input');
            const fileList = document.getElementById('file-list');
            const uploadBtn = document.getElementById('upload-btn');
            const clearBtn = document.getElementById('clear-btn');
            const usedSpaceEl = document.getElementById('used-space');
            const freeSpaceEl = document.getElementById('free-space');
            const usagePercentEl = document.getElementById('usage-percent');
            const progressBar = document.querySelector('.disk-progress .progress-bar');
            
            let files = [];
            let uploading = false;
            
            // 加载磁盘空间信息
            function loadDiskSpace() {
                fetch('/api/sysinfo')
                    .then(res => res.json())
                    .then(data => {
                        if (data.disk) {
                            // 直接使用返回的字节数
                            usedSpaceEl.textContent = formatBytes(data.disk.upload_used);
                            freeSpaceEl.textContent = formatBytes(data.disk.available);
                            const percent = Math.min(100, Math.round((data.disk.upload_used / data.disk.upload_total) * 100));
                            usagePercentEl.textContent = `${percent}%`;
                            progressBar.style.width = `${percent}%`;
                            
                            // 根据使用率设置颜色
                            if (percent > 90) {
                                progressBar.classList.add('bg-danger');
                            } else if (percent > 70) {
                                progressBar.classList.add('bg-warning');
                            } else {
                                progressBar.classList.add('bg-success');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('加载磁盘空间失败:', error);
                    });
            }
            
            // 格式化文件大小
            function formatBytes(bytes) {
                if (bytes === 0) return "0B";
                
                const k = 1024;
                const sizes = ["B", "KB", "MB", "GB", "TB"];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
            }
            
            // 渲染文件列表
            function renderFileList() {
                if (files.length === 0) {
                    fileList.innerHTML = `
                        <div class="text-center py-4">
                            <i class="bi bi-folder-plus display-4 text-muted mb-3"></i>
                            <p class="text-muted">暂无文件</p>
                            <p>添加文件开始上传</p>
                        </div>
                    `;
                    return;
                }
                
                let html = '';
                files.forEach((file, index) => {
                    html += `
                        <div class="file-item" data-index="${index}">
                            <div class="file-icon">
                                <i class="bi bi-file-earmark"></i>
                            </div>
                            <div class="file-info">
                                <div class="file-name">${file.name}</div>
                                <div class="file-size">${formatBytes(file.size)}</div>
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar" style="width: ${file.progress || 0}%"></div>
                                </div>
                            </div>
                            <div class="file-status status-${file.status || 'pending'}">
                                ${file.status === 'uploading' ? '上传中' : 
                                  file.status === 'completed' ? '已完成' : 
                                  file.status === 'failed' ? '失败' : '等待中'}
                            </div>
                        </div>
                    `;
                });
                
                fileList.innerHTML = html;
            }
            
            // 添加文件到列表
            function addFiles(newFiles) {
                for (let i = 0; i < newFiles.length; i++) {
                    const file = newFiles[i];
                    
                    // 检查文件是否已存在
                    const exists = files.some(f => f.name === file.name && f.size === file.size);
                    if (exists) continue;
                    
                    files.push({
                        name: file.name,
                        size: file.size,
                        file: file,
                        status: 'pending',
                        progress: 0
                    });
                }
                
                renderFileList();
            }
            
            // 处理拖放事件
            dropZone.addEventListener('dragover', function(e) {
                e.preventDefault();
                dropZone.classList.add('drag-over');
            });
            
            dropZone.addEventListener('dragleave', function() {
                dropZone.classList.remove('drag-over');
            });
            
            dropZone.addEventListener('drop', function(e) {
                e.preventDefault();
                dropZone.classList.remove('drag-over');
                
                if (e.dataTransfer.files.length > 0) {
                    addFiles(e.dataTransfer.files);
                }
            });
            
            // 点击拖放区域触发文件选择
            dropZone.addEventListener('click', function() {
                fileInput.click();
            });
            
            // 文件选择变化
            fileInput.addEventListener('change', function() {
                if (this.files.length > 0) {
                    addFiles(this.files);
                    this.value = ''; // 重置以允许选择相同文件
                }
            });
            
            // 清空文件列表
            clearBtn.addEventListener('click', function() {
                if (!uploading) {
                    files = [];
                    renderFileList();
                } else {
                    showMessage('上传过程中不能清空列表', 'warning');
                }
            });
            
            // 上传文件
            uploadBtn.addEventListener('click', function() {
                if (files.length === 0) {
                    showMessage('请先添加文件', 'warning');
                    return;
                }
                
                if (uploading) {
                    showMessage('上传正在进行中', 'warning');
                    return;
                }
                
                uploading = true;
                uploadBtn.disabled = true;
                uploadBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 上传中...';
                
                // 上传每个文件
                files.forEach((fileItem, index) => {
                    if (fileItem.status === 'completed') return;
                    
                    fileItem.status = 'uploading';
                    renderFileList();
                    
                    const formData = new FormData();
                    formData.append('file', fileItem.file);
                    
                    const xhr = new XMLHttpRequest();
                    
                    // 进度更新
                    xhr.upload.addEventListener('progress', function(e) {
                        if (e.lengthComputable) {
                            const percent = Math.round((e.loaded / e.total) * 100);
                            fileItem.progress = percent;
                            renderFileList();
                        }
                    });
                    
                    // 上传完成
                    xhr.addEventListener('load', function() {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.status === 'success') {
                                    fileItem.status = 'completed';
                                } else {
                                    fileItem.status = 'failed';
                                }
                            } catch {
                                fileItem.status = 'completed';
                            }
                        } else {
                            fileItem.status = 'failed';
                        }
                        
                        renderFileList();
                        checkUploadComplete();
                    });
                    
                    // 上传错误
                    xhr.addEventListener('error', function() {
                        fileItem.status = 'failed';
                        renderFileList();
                        checkUploadComplete();
                    });
                    
                    xhr.open('POST', '/api/multi_upload');
                    xhr.send(formData);
                });
            });
            
            // 检查所有文件是否上传完成
            function checkUploadComplete() {
                const allCompleted = files.every(file => 
                    file.status === 'completed' || file.status === 'failed');
                
                if (allCompleted) {
                    uploading = false;
                    uploadBtn.disabled = false;
                    uploadBtn.innerHTML = '<i class="bi bi-cloud-arrow-up"></i> 开始上传';
                    
                    // 更新磁盘空间信息
                    loadDiskSpace();
                    
                    // 统计结果
                    const completed = files.filter(f => f.status === 'completed').length;
                    const failed = files.filter(f => f.status === 'failed').length;
                    
                    if (failed > 0) {
                        showMessage(`上传完成! 成功: ${completed}个, 失败: ${failed}个`, 'success');
                    } else {
                        showMessage(`上传完成! 所有文件已成功上传`, 'success');
                    }
                }
            }
            
            // 初始加载磁盘空间信息
            loadDiskSpace();
        });
    </script>

    <!-- 模态窗口 -->
    <div id="modal" class="modal fade" tabindex="-1" aria-labelledby="modal-label" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal-label">消息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="modal-body">
                    模态窗口内容
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认对话框 -->
    <div id="confirm-modal" class="modal fade" tabindex="-1" aria-labelledby="confirm-label" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirm-label">确认操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="confirm-body">
                    您确定要执行此操作吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirm-yes">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="message-box" class="position-fixed top-5 end-5 z-50 d-none">
        <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto" id="message-title">提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body" id="message-text">
                消息内容
            </div>
        </div>
    </div>

    <script>
        // 显示模态窗口
        function showModal(title, content) {
            const modal = document.getElementById('modal');
            document.getElementById('modal-label').textContent = title;
            document.getElementById('modal-body').textContent = content;
            new bootstrap.Modal(modal).show();
        }
        
        // 显示确认对话框
        function showConfirm(title, content, callback) {
            const confirmModal = document.getElementById('confirm-modal');
            document.getElementById('confirm-label').textContent = title;
            document.getElementById('confirm-body').textContent = content;
            
            // 移除之前的事件监听器
            const confirmYes = document.getElementById('confirm-yes');
            const newConfirmYes = confirmYes.cloneNode(true);
            confirmYes.parentNode.replaceChild(newConfirmYes, confirmYes);
            
            // 添加新的事件监听器
            newConfirmYes.addEventListener('click', function() {
                if (callback && typeof callback === 'function') {
                    callback();
                }
                bootstrap.Modal.getInstance(confirmModal).hide();
            });
            
            new bootstrap.Modal(confirmModal).show();
        }
        
        // 显示消息提示
        function showMessage(message, type = 'info') {
            const messageBox = document.getElementById('message-box');
            const messageTitle = document.getElementById('message-title');
            const messageText = document.getElementById('message-text');
            
            // 设置消息类型样式
            const toast = messageBox.querySelector('.toast');
            toast.className = 'toast show';
            
            // 设置标题和内容
            if (type === 'success') {
                messageTitle.textContent = '成功';
                messageTitle.className = 'me-auto text-success';
            } else if (type === 'error') {
                messageTitle.textContent = '错误';
                messageTitle.className = 'me-auto text-danger';
            } else if (type === 'warning') {
                messageTitle.textContent = '警告';
                messageTitle.className = 'me-auto text-warning';
            } else {
                messageTitle.textContent = '提示';
                messageTitle.className = 'me-auto';
            }
            
            messageText.textContent = message;
            messageBox.classList.remove('d-none');
            
            // 3秒后自动隐藏
            setTimeout(function() {
                messageBox.classList.add('d-none');
            }, 3000);
        }
        
        // 深色模式切换功能
        document.addEventListener('DOMContentLoaded', function() {
            const themeToggle = document.getElementById('theme-toggle');
            const themeIcon = themeToggle.querySelector('i');
            
            // 检查本地存储或系统偏好
            const savedTheme = localStorage.getItem('theme') || 
                            (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            
            if (savedTheme === 'dark') {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeIcon.className = 'bi bi-sun';
                themeToggle.innerHTML = '<i class="bi bi-sun"></i> 浅色模式';
            }
            
            // 切换主题
            themeToggle.addEventListener('click', function() {
                const currentTheme = document.documentElement.getAttribute('data-theme');
                if (currentTheme === 'dark') {
                    document.documentElement.removeAttribute('data-theme');
                    localStorage.setItem('theme', 'light');
                    themeIcon.className = 'bi bi-moon';
                    themeToggle.innerHTML = '<i class="bi bi-moon"></i> 深色模式';
                } else {
                    document.documentElement.setAttribute('data-theme', 'dark');
                    localStorage.setItem('theme', 'dark');
                    themeIcon.className = 'bi bi-sun';
                    themeToggle.innerHTML = '<i class="bi bi-sun"></i> 浅色模式';
                }
            });
        });
    </script>
</body>
</html>
